package ru.spbu.math.seabattle.client.jms.common;

import java.io.Serializable;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;

public abstract class JmsHelper {

	protected Session session;

	protected MessageProducer producer;

	private Connection connection;

	public void start(String url, String queueName) throws JMSException {
		createSession(url);
		producer = createProducer(session, queueName);
	}

	public void start(String url, Destination destination) throws JMSException {
		createSession(url);
		producer = createProducer(session, destination);
	}

	protected MessageProducer createProducer(Session session, Destination destination) throws JMSException {
		return session.createProducer(destination);
	}

	protected abstract MessageProducer createProducer(Session session, String queueName) throws JMSException;

	public void send(Serializable message) throws JMSException {
		producer.send(createMessage(message));
	}

	public void sendFrom(Serializable message, Destination from) throws JMSException {
		ObjectMessage oMessage = createMessage(message);
		oMessage.setJMSReplyTo(from);
		producer.send(oMessage);
	}

	protected ObjectMessage createMessage(Serializable message) throws JMSException {
		return session.createObjectMessage(message);
	}

	public void shutdown() {
		try {
			connection.stop();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	public abstract Destination getDestination();

	public void createSession(String url) throws JMSException {
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);

		connection = connectionFactory.createConnection();
		connection.start();

		session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
	}
}
